// 引入 uni-ajax 模块
import ajax from 'uni-ajax'

import settings from '@/common/settings';
import {
	userLifeDataStore
} from '@/store/lifeDataStore';

// 创建请求实例
const instance = ajax.create({
	// 基地址
	baseURL: settings.devUrl
})

// 添加请求拦截器
instance.interceptors.request.use(
	(config) => {
		const lifeDataStore = userLifeDataStore();
		const {
			userInfo
		} = lifeDataStore;
		// 请求头
		config.header[settings.headerTokenName] = userInfo?.[settings.userTokenName] || '';
		// 是否显示加载中
		if (!settings.showLoading) return config;
		uni.showLoading({
			title: settings.loadingText,
			mask: true
		});
		return config;
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 添加响应拦截器
instance.interceptors.response.use(
	(response) => {
		if (response.data[settings.codeName] !== settings.successCode) {
			uni.showToast({
				title: response.data.msg
			})
			return Promise.reject(response.data)
		}
		uni.hideLoading()
		return response.data
	},
	(error) => {
		uni.hideLoading()
		return Promise.reject(error)
	}
)

// 导出实例
export default instance